<template>
  <div class="home">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="logo">商城系统</div>
          <div class="search">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">搜索</el-button>
              </template>
            </el-input>
          </div>
          <div class="actions">
            <template v-if="isLoggedIn">
              <el-button @click="$router.push('/cart')">购物车</el-button>
              <el-dropdown @command="handleCommand">
                <el-button>{{ username }}<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                    <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              <el-button @click="$router.push('/login')">登录</el-button>
              <el-button @click="$router.push('/register')">注册</el-button>
            </template>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <div class="categories">
          <el-menu mode="horizontal" :default-active="activeCategory" @select="handleCategorySelect">
            <el-menu-item v-for="category in categories" :key="category.id" :index="category.id.toString()">
              {{ category.name }}
            </el-menu-item>
          </el-menu>
        </div>
        
        <div class="product-list">
          <el-row :gutter="20">
            <el-col v-for="product in products" :key="product.id" :span="6">
              <el-card :body-style="{ padding: '0px' }" class="product-card">
                <img :src="product.imageUrl" class="product-image">
                <div class="product-info">
                  <h3>{{ product.name }}</h3>
                  <div class="price">¥{{ product.price }}</div>
                  <div class="actions">
                    <el-button type="primary" size="small" @click="addToCart(product)">
                      加入购物车
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const store = useStore()
const router = useRouter()

const searchKeyword = ref('')
const activeCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const products = ref([])
const categories = ref([])

const isLoggedIn = computed(() => store.state.token)
const username = computed(() => store.state.user?.username)

const loadCategories = async () => {
  try {
    const response = await store.dispatch('product/getCategories')
    categories.value = response
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const loadProducts = async () => {
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      keyword: searchKeyword.value,
      categoryId: activeCategory.value || undefined
    }
    const response = await store.dispatch('product/getProducts', params)
    products.value = response.content
    total.value = response.totalElements
  } catch (error) {
    ElMessage.error('加载商品列表失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

const handleCategorySelect = (categoryId: string) => {
  activeCategory.value = categoryId
  currentPage.value = 1
  loadProducts()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadProducts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadProducts()
}

const addToCart = async (product: any) => {
  if (!isLoggedIn.value) {
    router.push('/login')
    return
  }
  
  try {
    await store.dispatch('cart/addToCart', {
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    ElMessage.error('添加购物车失败')
  }
}

const handleCommand = (command: string) => {
  switch (command) {
    case 'orders':
      router.push('/orders')
      break
    case 'profile':
      router.push('/user/profile')
      break
    case 'logout':
      store.dispatch('logout')
      router.push('/login')
      break
  }
}

onMounted(() => {
  loadCategories()
  loadProducts()
})
</script>

<style scoped>
.home {
  min-height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo {
  font-size: 24px;
  font-weight: bold;
}

.search {
  width: 400px;
}

.categories {
  margin-bottom: 20px;
}

.product-card {
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  margin: 10px 0;
}

.actions {
  display: flex;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style> 